#include <iostream>
#include <random>
#include <dds/dds.h>
#include "end_atomic_0822_transmission_control_service.h"
#include "../../../include/log_client/LogClient.h"

// DDS实体句柄
static dds_entity_t participant;
static dds_entity_t topic;
static dds_entity_t subscriber;
static dds_entity_t reader;

// 简化结构体名称
typedef end_atomic_0822_transmission_control_service_TransportOutput TransportOutput;

// 清理DDS资源
static void cleanup()
{
    if (reader != DDS_HANDLE_NIL)
        dds_delete(reader);
    if (subscriber != DDS_HANDLE_NIL)
        dds_delete(subscriber);
    if (topic != DDS_HANDLE_NIL)
        dds_delete(topic);
    if (participant != DDS_HANDLE_NIL)
        dds_delete(participant);
}

// 生成随机传输控制数据（用于测试）
TransportOutput generate_random_transport_data()
{
    static std::mt19937 rng(std::random_device{}());
    std::uniform_int_distribution<int32_t> result_dist(0, 1);       // 传输结果：0-成功，1-失败
    std::uniform_int_distribution<int32_t> len_dist(0, 1024);       // 实际发送长度：0-1024字节
    std::uniform_int_distribution<int32_t> type_dist(0, 3);         // 返回类型：0-3

    TransportOutput data;
    data.transfer_result = result_dist(rng);
    data.actual_sent_len = len_dist(rng);
    data.return_type = type_dist(rng);
    return data;
}

int main()
{
    // 初始化日志
    LogClient::getInstance().init("end_atomic_0822_transmission_control", "end_atomic_0822_transmission_control");

    dds_return_t rc;
    void* samples[1];       // 存储DDS样本的数组（最多1个样本）
    dds_sample_info_t info; // 样本元信息

    // 1. 初始化DDS参与者
    participant = dds_create_participant(DDS_DOMAIN_DEFAULT, NULL, NULL);
    if (participant < 0)
    {
        std::cerr << "错误：创建参与者失败，原因：" << dds_strretcode(-participant) << std::endl;
        LogClient::getInstance().logError("创建参与者失败，原因：" + std::string(dds_strretcode(-participant)));
        cleanup();
        return EXIT_FAILURE;
    }

    // 2. 创建主题（与发布者保持一致）
    topic = dds_create_topic(
        participant,
        &end_atomic_0822_transmission_control_service_TransportOutput_desc,
        "end_atomic_0822_transmission_control_service",  // 主题名称
        NULL, NULL);
    if (topic < 0)
    {
        std::cerr << "错误：创建主题失败，原因：" << dds_strretcode(-topic) << std::endl;
        LogClient::getInstance().logError("创建主题失败，原因：" + std::string(dds_strretcode(-topic)));
        cleanup();
        return EXIT_FAILURE;
    }

    // 3. 创建订阅者
    subscriber = dds_create_subscriber(participant, NULL, NULL);
    if (subscriber < 0)
    {
        std::cerr << "错误：创建订阅者失败，原因：" << dds_strretcode(-subscriber) << std::endl;
        LogClient::getInstance().logError("创建订阅者失败，原因：" + std::string(dds_strretcode(-subscriber)));
        cleanup();
        return EXIT_FAILURE;
    }

    // 4. 创建数据读取器
    dds_qos_t* qos = dds_create_qos();
    dds_qset_reliability(qos, DDS_RELIABILITY_RELIABLE, DDS_SECS(10));
    dds_qset_history(qos, DDS_HISTORY_KEEP_LAST, 10);

    reader = dds_create_reader(subscriber, topic, qos, NULL);
    dds_delete_qos(qos);

    if (reader < 0)
    {
        std::cerr << "错误：创建读取器失败，原因：" << dds_strretcode(-reader) << std::endl;
        LogClient::getInstance().logError("创建读取器失败，原因：" + std::string(dds_strretcode(-reader)));
        cleanup();
        return EXIT_FAILURE;
    }

    std::cout << "DDS传输控制服务订阅者已启动，等待接收数据..." << std::endl;
    std::cout << "主题: end_atomic_0822_transmission_topic" << std::endl;
    std::cout << "按Ctrl+C终止程序" << std::endl;
    LogClient::getInstance().logInfo("DDS传输控制服务订阅者已启动，等待接收数据...\n主题: end_atomic_0822_transmission_topic\n按Ctrl+C终止程序");

    // 5. 循环读取数据
    int count = 0;
    while (true)
    {
        // 分配样本内存
        samples[0] = end_atomic_0822_transmission_control_service_TransportOutput__alloc();
        if (samples[0] == NULL)
        {
            std::cerr << "错误：分配样本内存失败" << std::endl;
            LogClient::getInstance().logError("分配样本内存失败");
            cleanup();
            return EXIT_FAILURE;
        }

        // 从读取器中获取数据
        rc = dds_take(reader, samples, &info, 1, 1);
        if (rc < 0)
        {
            std::cerr << "错误：dds_take失败，原因：" << dds_strretcode(-rc) << std::endl;
            LogClient::getInstance().logError("dds_take失败，原因：" + std::string(dds_strretcode(-rc)));
            end_atomic_0822_transmission_control_service_TransportOutput_free(samples[0], DDS_FREE_ALL);
            cleanup();
            return EXIT_FAILURE;
        }

        // 检查是否有有效数据
        if (rc > 0 && info.valid_data)
        {
            // 转换为目标结构体类型
            TransportOutput* data = (TransportOutput*)samples[0];
            count++;

            // 构建日志信息
            const char* result_str = (data->transfer_result == 0) ? "成功" : "失败";
            const char* type_str[] = {"成功", "警告", "错误", "超时"};
            int32_t type_idx = (data->return_type >= 0 && data->return_type < 4) ? data->return_type : 0;

            std::string log_info = "接收到传输控制数据，第" + std::to_string(count) + "次\n";
            log_info += "源时间戳: " + std::to_string(info.source_timestamp) + "\n";
            log_info += "传输结果: " + std::string(result_str) + " (" + std::to_string(data->transfer_result) + ")\n";
            log_info += "实际发送长度: " + std::to_string(data->actual_sent_len) + " 字节\n";
            log_info += "返回类型: " + std::string(type_str[type_idx]) + " (" + std::to_string(data->return_type) + ")\n";

            std::cout << log_info << std::endl;
            LogClient::getInstance().logInfo(log_info);
        }

        // 释放样本内存
        end_atomic_0822_transmission_control_service_TransportOutput_free(samples[0], DDS_FREE_ALL);

        // 休眠100ms避免CPU占用过高
        dds_sleepfor(DDS_MSECS(100));
    }

    // 清理资源（实际不会执行到）
    cleanup();
    return EXIT_SUCCESS;
}